package com.cinema.api.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cinema.api.constant.Roles;
import com.cinema.api.mapper.RoleMapper;
import com.cinema.api.model.entity.Role;
import com.cinema.api.model.entity.Worker;
import com.cinema.api.mapper.WorkerMapper;
import com.cinema.api.model.enums.ResultCodeEnum;
import com.cinema.api.model.exception.BizException;
import com.cinema.api.model.vo.FilmVO;
import com.cinema.api.model.vo.LoginVO;
import com.cinema.api.service.RoleService;
import com.cinema.api.service.WorkerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cinema.api.utils.BaseUtil;
import com.cinema.api.utils.DataTimeUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhh
 * @since 2021-12-31
 */
@Service
public class WorkerServiceImpl extends ServiceImpl<WorkerMapper, Worker> implements WorkerService {

    @Resource
    private WorkerMapper workerMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleService roleService;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public Worker login(LoginVO loginVO) throws Exception {
        QueryWrapper<Worker> wrapper = new QueryWrapper<>();
        wrapper.in("username", loginVO.getUsername())
                .eq("is_delete", 0);
        Worker worker = workerMapper.selectOne(wrapper);
        if (BaseUtil.isEmpty(worker)) {
            throw new BizException(ResultCodeEnum.USERNAME_PASSWORD_NOT_FOUND);
        }
        if (!bCryptPasswordEncoder.matches(loginVO.getPassword(), worker.getPassword())) {
            throw new BizException(ResultCodeEnum.USERNAME_PASSWORD_NOT_FOUND);
        }
        if (!worker.getEntry()) {
            throw new BizException(20041, "员工已离职！");
        }
        return worker;
    }

    /**
     * 查询全部员工
     */
    @Override
    public List<Worker> findAll() {
        QueryWrapper<Worker> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", 0);
        return workerMapper.selectList(wrapper);
    }

    /**
     * 查询全部员工
     */
    @Override
    public PageInfo<Worker> findAllByPage(int page, int limit) {
        PageHelper.startPage(page, limit);
        QueryWrapper<Worker> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete", 0);
        List<Worker> workers = workerMapper.selectList(wrapper);
        return new PageInfo<>(workers);
    }

    @Override
    public PageInfo<Worker> filmLikeList(int page, int limit, String username) {
        // 使用Mybatis分页插件
        PageHelper.startPage(page, limit);
        List<Worker> like = workerMapper.findByLike(username);
        return new PageInfo<>(like);
    }

    /**
     * 添加或更新员工信息
     */
    @Override
    public void createOrUpdate(Worker worker) throws Exception{
        QueryWrapper<Worker> wrapper = new QueryWrapper<>();
        wrapper.in("username", worker.getUsername())
                .eq("is_delete", 0);
        Worker workerOne = workerMapper.selectOne(wrapper);
        if (BaseUtil.isEmpty(worker.getId())) {
            // 添加新增员工
            // 判断用户名是否已存在
            if (workerOne != null) {
                throw new BizException(1001, "用户名已存在");
            }
            worker.setEntry(true);
            worker.setPassword(bCryptPasswordEncoder.encode(worker.getPassword()));
            worker.setId(UUID.randomUUID().toString());
            worker.setCreateTime(DataTimeUtil.getNowTimeString());
            worker.setIsDelete(0);
            workerMapper.insert(worker);
            // 添加员工权限
            Role role = new Role(UUID.randomUUID().toString(), worker.getId(), Roles.ROLE_WORKER, DataTimeUtil.getNowTimeString(), 0);
            roleMapper.insert(role);
        } else {
            // 更新
            // 判断用户名是否重复-(是否存在且不是本身)
            if (workerOne != null && !workerOne.getId().equals(worker.getId())) {
                throw new BizException(1001, "用户名已存在");
             }
            // 进行信息更新
            worker.setPassword(bCryptPasswordEncoder.encode(worker.getPassword()));
            worker.setUpdateTime(DataTimeUtil.getNowTimeString());
            workerMapper.updateById(worker);
        }
    }

    /**
     *  根据id查询员工信息
     */
    @Override
    public Worker findById(String id) {
        Worker worker = workerMapper.selectById(id);
        return worker;
    }

    /**
     * 根据id删除员工以及权限信息
     */
    @Override
    public void deleteById(String id) {
        // 删除员工信息
        workerMapper.deleteById(id);
        // 删除员工信息相关联的权限
        roleService.deleteAllByWID(id);
    }


}
